package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author wangyuqing
 * @since 2024-08-26
 */
//@Service
@RequiredArgsConstructor
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {
    private final RabbitMqHelper mqHelper;


    /**
     * 1.点赞或取消点赞方法
     *
     * @param likeRecordFormDTO 点赞业务数据DTO
     */
    @Override
    public void likeOrUnLike(LikeRecordFormDTO likeRecordFormDTO) {
        //1、基于前端参数，判断点赞还是取消点赞，根据判断结果，执行点赞、取消点赞，返回是否成功
        Boolean result = likeRecordFormDTO.getLiked() ? like(likeRecordFormDTO) : unLike(likeRecordFormDTO);
        //2、判断是否执行成功，如果失败，直接结束
        if (!result) {
            return;
        }
        //3.如果执行成功，则统计点赞次数
        Integer likeTimes = lambdaQuery().eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId()).count();
        // 4、发送MQ消息，通知业务方修改点赞数
        mqHelper.send(LIKE_RECORD_EXCHANGE,
                StringUtils.format(LIKED_TIMES_KEY_TEMPLATE, likeRecordFormDTO.getBizType()),
                LikedTimesDTO.of(likeRecordFormDTO.getBizId(), likeTimes));
    }

    /**
     * 取消点赞方法
     *
     * @param likeRecordFormDTO
     * @return
     */
    private Boolean unLike(LikeRecordFormDTO likeRecordFormDTO) {
        return remove(new QueryWrapper<LikedRecord>().lambda()
                .eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId())
                .eq(LikedRecord::getUserId, UserContext.getUser()));
    }

    /**
     * 点赞方法
     *
     * @param likeRecordFormDTO
     * @return
     */
    private Boolean like(LikeRecordFormDTO likeRecordFormDTO) {
        //1、查询点赞记录，如果存在，直接返回false
        Integer count = lambdaQuery()
                .eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId())
                .eq(LikedRecord::getUserId, UserContext.getUser()).count();
        if (count > 0) {
            return false;
        }
        //2、如果不存在，则新增点赞记录，返回true
        LikedRecord likedRecord = new LikedRecord()
                .setBizId(likeRecordFormDTO.getBizId())
                .setBizType(likeRecordFormDTO.getBizType())
                .setUserId(UserContext.getUser());
        return save(likedRecord);
    }


    /**
     * 2.根据业务ID查询该用户对业务的点赞状态
     *
     * @param bizIds 回答或评论的id集合
     */
    @Override
    public Set<Long> isLiked(List<Long> bizIds) {
        //1.查询点赞记录
        List<LikedRecord> list = lambdaQuery()
                .select(LikedRecord::getBizId)
                .eq(LikedRecord::getUserId, UserContext.getUser())
                .in(LikedRecord::getBizId, bizIds)
                .list();
        // 2、返回已经点赞的业务ID集合
        return list.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());
    }

    /**
     * 3、定时读取zset中的点赞数并发送消息至业务方 - 更新点赞数（Day6 -随堂3）
     *
     * @param bizType
     * @param maxLikedTimes
     */
    @Override
    public void readLikedTimesAndSendMessage(String bizType, Integer maxLikedTimes) {

    }
}
